package com.zhentao.config;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 百度AI接口Token获取工具类
 * 用于获取百度AI服务的访问令牌
 */
public class TokenUtil1 {
    
    private static final OkHttpClient client = new OkHttpClient().newBuilder()
            .readTimeout(30, TimeUnit.SECONDS)
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .build();

    /**
     * 获取百度AI访问令牌
     * @param apiKey 百度AI API Key
     * @param secretKey 百度AI Secret Key
     * @return 访问令牌
     * @throws IOException 网络请求异常
     */
    public static String getAccessToken(String apiKey, String secretKey) throws IOException {
        String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials"
                + "&client_id=" + apiKey
                + "&client_secret=" + secretKey;

        Request request = new Request.Builder()
                .url(url)
                .get()
                .addHeader("Content-Type", "application/json")
                .build();
                
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求失败: " + response.code() + " " + response.message());
            }
            
            String json = response.body().string();
            JSONObject jsonObject = new JSONObject(json);
            
            if (jsonObject.has("error")) {
                throw new IOException("获取token失败: " + jsonObject.getString("error_description"));
            }
            
            return jsonObject.getString("access_token");
        }
    }

    /**
     * 测试方法 - 仅用于开发测试
     * 注意：生产环境中不应将API密钥硬编码在代码中
     */
    public static void main(String[] args) {
        try {
            // 注意：生产环境中应该从配置文件或环境变量中读取
            String apiKey = "uJwxkU0uupwbjYkkCA4PXe28";
            String secretKey = "tn2rln1sFmMY3L5b0I1UY8Z0ehyUgOtg";
            
            String accessToken = getAccessToken(apiKey, secretKey);
            System.out.println("access_token: " + accessToken);
        } catch (IOException e) {
            System.err.println("获取token失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}